package com.gitee.webdav;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.NioUtil;
import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.gitee.webdav.kernel.Constants;
import com.gitee.webdav.kernel.Remark;
import com.gitee.webdav.kernel.ResourceDispatcher;
import com.gitee.webdav.kernel.ResourceMonitor;
import com.gitee.webdav.logger.LoggerFactory;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.smartboot.http.server.HttpBootstrap;
import org.smartboot.http.server.impl.Request;

/**
 * @author hongda.li@hand-china.com
 */
@Slf4j
public class HomeStarter {

    @Getter
    @Remark("运行时间")
    private static long runtime;

    @Getter
    @Remark("监听端口")
    private static int port;

    @Getter
    @Remark("根目录挂载路径")
    private static String rootPath;

    @Getter
    @Remark("读缓冲区大小")
    private static int readBufferSize;

    @Getter
    @Remark("写缓冲区大小")
    private static int writeBufferSize;

    public static void main(String[] args) {
        loadConfiguration();

        HttpBootstrap bootstrap = new HttpBootstrap();
        bootstrap.setPort(port);
        bootstrap.httpHandler(new ResourceDispatcher());
        bootstrap.configuration()
                // 禁用低内存模式
                .setLowMemory(false)
                // 禁用Banner
                .bannerEnabled(false)
                // 读缓冲区大小
                .readBufferSize(readBufferSize)
                // 写缓冲区大小
                .writeBufferSize(writeBufferSize)
                // 主机地址
                .host(NetUtil.getLocalhostStr())
                // 服务端名称
                .serverName(HomeStarter.class.getSimpleName())
                // 线程数
                .threadNum(RuntimeUtil.getProcessorCount())
                // 码流速率监控
                .addPlugin(new ResourceMonitor());
        bootstrap.start();

        runtime = System.currentTimeMillis();
        RuntimeUtil.addShutdownHook(bootstrap::shutdown);
    }

    private static void loadConfiguration() {
        port = Convert.toInt(System.getProperty(Constants.Configure.PORT), Constants.Configure.PORT_VALUE);
        rootPath = CharSequenceUtil.blankToDefault(System.getProperty(Constants.Configure.ROOT), Constants.Configure.ROOT_VALUE);
        readBufferSize = Convert.toInt(System.getProperty(Constants.Configure.READ_BUFFER), NioUtil.DEFAULT_MIDDLE_BUFFER_SIZE);
        writeBufferSize = Convert.toInt(System.getProperty(Constants.Configure.WRITE_BUFFER), NioUtil.DEFAULT_MIDDLE_BUFFER_SIZE);

        log.info("监听端口号 : {}", port);
        log.info("主机地址 : {}", NetUtil.getLocalhostStr());
        log.info("根目录挂载路径 : {}", rootPath);
        log.info("读缓冲区大小 : {}", DataSizeUtil.format(readBufferSize));
        log.info("写缓冲区大小 : {}", DataSizeUtil.format(writeBufferSize));

        LoggerFactory.disabled(Request.class);
    }
}
